package it.fc.mail;

import it.fc.exceptions.FcException;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.SimpleEmail;
import org.apache.log4j.Logger;

public class MailManager {

    private Properties props;
    private static Logger log = Logger.getLogger(MailManager.class);

    public MailManager() throws FcException {
        log.debug("Parsing mail properties...");
        loadProperties();
    }

 
    public void sendMail(String subject, String body, String to) throws EmailException {

        SimpleEmail email = new SimpleEmail();
        email.setHostName(props.getProperty(MailProperties.SMTP_HOST));
        email.addTo(to);
        email.setSubject(subject);
        email.setMsg(body);
        email.setFrom(props.getProperty(MailProperties.ADDR_FROM), props.getProperty(MailProperties.NAME_FROM));
        email.send();

    }

    private void loadProperties() throws FcException{
        props = new Properties();
        
        try {
            URL url = Thread.currentThread().getContextClassLoader().getResource("mailconfig.properties");
            props.load(url.openStream());
            
        } catch (FileNotFoundException e) {
            log.debug("File properties not bound!");
            throw new FcException("mailconfig.properties not bound!");
        } catch (IOException e) {
            log.debug("File properties not bound!");
            throw new FcException("mailconfig.properties not bound!");
        }
    }

 
    public void sendHTMLMail(String subject, String body, String to) throws EmailException {

        HtmlEmail email = new HtmlEmail();
        email.setHostName(props.getProperty(MailProperties.SMTP_HOST));
        email.addTo(to);
        email.setFrom(props.getProperty(MailProperties.ADDR_FROM), props.getProperty(MailProperties.NAME_FROM));
        email.setSubject(subject);
        email.setHtmlMsg(body);
        email.setTextMsg("Your email client does not support HTML messages");
        email.send();

    }
}
